package com.dty.common.utils;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.stereotype.Component;

import javax.jms.*;
import java.util.Map;

public class ActiveMQBroadcasterUtil {

	private Connection connection;
	private Session session;
	private MessageProducer producer;

	public ActiveMQBroadcasterUtil(String brokerUrl, String user, String password) throws JMSException {
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
		connection = connectionFactory.createConnection(user, password);
		connection.start();

		session = connection.createSession(Boolean.TRUE, javax.jms.Session.AUTO_ACKNOWLEDGE);
		producer = session.createProducer(null);
		producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
	}

	public void broadcast(String topic, Map<String, Object> infoMap) throws JMSException {
		MapMessage mapMsg = session.createMapMessage();
		for(String s:infoMap.keySet()){
			if (infoMap.get(s) instanceof String) {
				mapMsg.setString(s, (String) infoMap.get(s));
			} else if (infoMap.get(s) instanceof Integer) {
				mapMsg.setInt(s, (Integer) infoMap.get(s));
			} else if (infoMap.get(s) instanceof Double) {
				mapMsg.setDouble(s, (Double) infoMap.get(s));
			}
		}
		Destination destination = session.createTopic(topic);
		producer.send(destination, mapMsg);
	}

	public void close() throws JMSException {
		session.commit();
		producer.close();
		session.close();
		connection.close();
	}
}